#include "include/loginDlg.h"
#include "include/importDlg.h"
#include "include/exportDlg.h"
#include "include/mainWindow.h"
#include "include/typeSearchDlg.h"
#include "include/ctrlSettingDlg.h"
#include "include/regionSearchDlg.h"
#include "include/keyWordSearchDlg.h"

#include "include/serialbuffer.h"
#include "include/protocols.h"


#include <QtGui>
#include <QDebug>
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QString>
#include <QTextCodec>
#include <QByteArray>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
//   QTextCodec *tc =  QTextCodec::codecForName("UTF8");
    init();
    initSerial();
    createAction();
    createToolBars();
    createStatusBars();
    initItem();
}

void MainWindow::init()
{
    feedbackTemp= 0;
    malfunctionTemp = 0;
    feedbackFlag = 0;
    malfunctionFlag = 0;

    displayMode = true;//初始化为复杂显示模式
    myTimerId = 0;//定时器间隔
    pageSeq = 1;//页序号
    itemStatusId = 0;

    groupBox = new QGroupBox(this);

    timeLabel = new QLabel(QString::fromUtf8(" "), this);
    connState = new QLabel(QString::fromUtf8("主机连接状态:"), this);
    conn = new QLabel(QString::fromUtf8("正常"), this);
    itemState = new QLabel(QString::fromUtf8("A区01栋01层101房:   "), this);
    item = new QLabel(QString::fromUtf8("正常"), this);
    uIcon = new QLabel(QString::fromUtf8(" "), this);
    uIcon->setFixedWidth(30);
    uIcon->setStyleSheet(QString::fromUtf8("image : url(:/image/devIcon/no.png)"));

    setFixedSize(800, 480);
    setCentralWidget(groupBox);
    //setWindowTitle(QString::fromUtf8("手控盘"));
    setWindowFlags(Qt::FramelessWindowHint);
    //setWindowIcon(QIcon(":/image/winIcon/sj.jpg"));
}

void MainWindow::initSerial()
{
    dev_serial = new MyUart;
    int fd = dev_serial->getFileDescriptor();
    if( fd != -1 )
    {
        uart_notifier = new QSocketNotifier(fd,QSocketNotifier::Read,this);
        connect( uart_notifier, SIGNAL(activated(int)), this, SLOT(uartDataCame()) );
    }
    app_data_frame = new SerialFrame;
    msg_processor = new MsgProc(this);
    connect( this, SIGNAL(sig_aplDataComing()), msg_processor, SLOT(aplDataCame()) );
    connect( msg_processor, SIGNAL(sig_sendMsg(QByteArray)), this, SLOT(slot_send_frame(QByteArray)) );
    connect(msg_processor, SIGNAL(handleData(QByteArray &)), this, SLOT(handleSerialData(QByteArray &)));
}

void MainWindow::createAction()
{
    importConf = new QAction(QString::fromUtf8("导入"), this);
    //importConf->setIcon(QIcon(":/image/toolBarIcon/import.png"));
    connect(importConf, SIGNAL(triggered()), this, SLOT(importConfSlot()));

    exportConf = new QAction(QString::fromUtf8("导出"), this);
    //exportConf->setIcon(QIcon(":/image/toolBarIcon/export.png"));
    connect(exportConf, SIGNAL(triggered()), this, SLOT(exportConfSlot()));

    ctrlSetting = new QAction(QString::fromUtf8("设置"), this);
    //ctrlSetting->setIcon(QIcon(":/image/toolBarIcon/settings.png"));
    connect(ctrlSetting, SIGNAL(triggered()), this, SLOT(ctrlSettingSlot()));

    keyWordSearch = new QAction(QString::fromUtf8("关键字查询"), this);
    //keyWordSearch->setIcon(QIcon(":/image/toolBarIcon/keyWord.png"));
    connect(keyWordSearch, SIGNAL(triggered()), this, SLOT(keyWordSearchSlot()));

    regionSearch = new QAction(QString::fromUtf8("区域查询"), this);
    //regionSearch->setIcon(QIcon(":/image/toolBarIcon/region.png"));
    connect(regionSearch, SIGNAL(triggered()), this, SLOT(regionSearchSlot()));

    typeSearch = new QAction(QString::fromUtf8("类型查询"), this);
    //typeSearch->setIcon(QIcon(":/image/toolBarIcon/type.png"));
    connect(typeSearch, SIGNAL(triggered()), this, SLOT(typeSearchSlot()));

    simpleItemDisPlay = new QAction(QString::fromUtf8("显示切换"), this);
    //simpleItemDisPlay->setIcon(QIcon(":/image/toolBarIcon/simple.png"));
    connect(simpleItemDisPlay, SIGNAL(triggered()), this, SLOT(switchDisPlaySlot()));

    clear = new QAction(QString::fromUtf8("清除闪烁"), this);
    connect(clear, SIGNAL(triggered()), this, SLOT(clearSlot()));

    pageUp = new QAction(QString::fromUtf8("上一页"), this);
    //pageUp->setIcon(QIcon(":/image/toolBarIcon/previous.png"));
    connect(pageUp, SIGNAL(triggered()), this, SLOT(pageSeqDesSlot()));

    pageDown = new QAction(QString::fromUtf8("下一页"), this);
    //pageDown->setIcon(QIcon(":/image/toolBarIcon/next.png"));
    connect(pageDown, SIGNAL(triggered()), this, SLOT(pageSeqIncSlot()));

    quit = new QAction(QString::fromUtf8("退出"), this);
    connect(quit, SIGNAL(triggered()), this, SLOT(close()));
}

void MainWindow::createToolBars()
{
    toolBar = addToolBar(QString::fromUtf8("工具栏"));
    toolBar->addAction(importConf);
    toolBar->addAction(exportConf);
    toolBar->addAction(ctrlSetting);
    toolBar->addSeparator();
    //toolBar->addAction(typeSearch);
    toolBar->addAction(regionSearch);
    toolBar->addAction(keyWordSearch);
    toolBar->addSeparator();
    toolBar->addAction(simpleItemDisPlay);
    toolBar->addSeparator();
    toolBar->addAction(clear);
    toolBar->addAction(pageUp);
    toolBar->addAction(pageDown);
    toolBar->addAction(quit);
}

void MainWindow::clearSlot()
{
    malfunctionFlag = 0;
    feedbackFlag = 0;
}

void MainWindow::createStatusBars()
{
    QLabel *emptyStr = new QLabel(QString::fromUtf8("       "), this);
    statusBar()->setStyleSheet(QString::fromUtf8("QStatusBar::item{border: 0px}"));
    statusBar()->setSizeGripEnabled(false);  
    statusBar()->addWidget(connState);
    statusBar()->addWidget(conn);
    statusBar()->addWidget(emptyStr);
    statusBar()->addWidget(itemState);
    statusBar()->addWidget(item);
    statusBar()->addPermanentWidget(timeLabel);
    statusBar()->addPermanentWidget(uIcon);
}

void MainWindow::handleSerialData(QByteArray &msg)
{
    qDebug() << "wocaoya";
    unsigned char TI = msg[0];
    unsigned char src_addr = msg[1];
    unsigned char des_addr = msg[2];
    unsigned char data_len = msg[3];
    unsigned char msgType = msg[5];

    switch( TI )
    {
    case TI_SOH:
        if(msgType==MSG_FIRE)//火警
        {
            qDebug() << "fire lai le";
        }
        else if(msgType==MSG_FEDBACK)
        {
            qDebug() << "feedback lai le";
        }
        else if(msgType==MSG_FAULT)
        {
            qDebug() << "sheding lai le";
        }
        break;

    case TI_BCSOH:
        break;

    default:
        break;
    }

}

void MainWindow::uartDataCame()
{
    int cnt = dev_serial->readRawData();
    if( cnt > 0 )
    {
        qDebug()<<cnt<<"bytes data read ";
        app_data_frame->extractAPLframe();
        if(aplRecvBuffer::Instance()->getBuffer().isEmpty() == false )
        {
            qDebug()<<"get application layer data";
            emit sig_aplDataComing();
        }
    }
}

void MainWindow::slot_send_frame(QByteArray msg)
{
    app_data_frame->generateDLLframe(msg);
    dev_serial->writeRawData(msg);
    qDebug() << msg;
}

void MainWindow::displayTime()
{
    int y = QDateTime::currentDateTime().date().year();
    int m = QDateTime::currentDateTime().date().month();
    int d = QDateTime::currentDateTime().date().day();
    QString strTime = QDateTime::currentDateTime().time().toString();

    timeLabel->setText(strTime + " " + QString::number(y) + "/" + QString::number(m) + "/" + QString::number(d));
}

void MainWindow::updateStatusBars()
{

}

void MainWindow::initItem()
{
    numOfTotalItem = getNumOfTotalItem();
    qDebug() << "总的个数：" << numOfTotalItem;
    maxPageSeq = getMaxPages(numOfTotalItem);
    qDebug() << "最大页数：" << maxPageSeq;
    displayItem();
}

void MainWindow::displayItem()
{
    int i = 0;
    int count = 0;
    QString areaTemp = "";
    QString ridgepoleTemp = "";
    QString layerTemp = "";
    QString roomTemp = "";
    QString devNameTemp = "";

    if(numOfTotalItem != 0)
    {
        QSqlDatabase::database().transaction();
        QSqlQuery query;
        query.exec(QString::fromUtf8("select id, area, ridgepole, layer, room, devName from itemInfo limit %1, %2").arg((pageSeq-1)*20).arg(ITEM_NUM_OF_PERPAGE));
        while(query.next())
        {
            if(displayMode)
            {
                mItem[i] = new MainItem(this);

                mItem[i]->SetId(query.value(0).toString());

                areaTemp = query.value(1).toString();
                ridgepoleTemp = query.value(2).toString();
                layerTemp = query.value(3).toString();
                roomTemp = query.value(4).toString();
                devNameTemp = query.value(5).toString();

                QString pos = areaTemp + ridgepoleTemp + layerTemp + roomTemp;
                QTextCodec *utf8 = QTextCodec::codecForName("UTF8");
                QByteArray qst2qba = pos.toLatin1().data();//QString转到QByteArray.默认的QString编码方式是Latin-1,坑死了！
                QString qba2qst = utf8->toUnicode(qst2qba);//QByteArray转到QString
                mItem[i]->SetPos(qba2qst);
                if(devNameTemp == "排烟阀")
                {
                    mItem[i]->icon->setStyleSheet(QString::fromUtf8("image : url(:/image/devIcon/smoke.png)"));
                }
                else if(devNameTemp == "消防水泵阀")
                {
                    mItem[i]->icon->setStyleSheet(QString::fromUtf8("image : url(:/image/devIcon/pump.png)"));
                }
                else if(devNameTemp == "消防警报铃")
                {
                    mItem[i]->icon->setStyleSheet(QString::fromUtf8("image : url(:/image/devIcon/bell.png)"));
                }
                else if(devNameTemp == "消防广播")
                {
                    mItem[i]->icon->setStyleSheet(QString::fromUtf8("image : url(:/image/devIcon/broadcast.png)"));
                }
                //mItem[i]->SetIcon(devNameTemp);
            }
            else
            {
                uItem[i] = new UndefinedItem(this);
                uItem[i]->SetId(query.value(0).toString());
            }
            i++;
        }
        QGridLayout *gridLayout = new QGridLayout;
        count = i;
        for(i=0; i<count; i++)
        {
            if(displayMode)
            {
                gridLayout->addWidget(mItem[i], i/5, i%5);
            }
            else
            {
                gridLayout->addWidget(uItem[i], i/5, i%5);
            }

        }

        if(count < ITEM_NUM_OF_PERPAGE)
        {
            for(; i<ITEM_NUM_OF_PERPAGE; i++)
            {
                if(displayMode)
                {
                    mItem[i] = new MainItem;
                    gridLayout->addWidget(mItem[i], i/5, i%5);
                }
                else
                {
                    uItem[i] = new UndefinedItem;
                    gridLayout->addWidget(uItem[i], i/5, i%5);
                }

            }
        }
        groupBox->close();
        groupBox = new QGroupBox(this);
        setCentralWidget(groupBox);
        groupBox->setLayout(gridLayout);

        QSqlDatabase::database().commit();
    }
}

void MainWindow::importConfSlot()
{
    ImportDlg *iDlg = new ImportDlg();
    connect(iDlg, SIGNAL(importFinished()), this, SLOT(initItem()));
    iDlg->show();
}

void MainWindow::exportConfSlot()
{
    ExportDlg *eDlg = new ExportDlg();
    eDlg->show();
}

void MainWindow::ctrlSettingSlot()
{
    CtrlSettingDlg *csDlg = new CtrlSettingDlg();
    LoginDlg *lDlg = new LoginDlg();

    if(lDlg->exec() == QDialog::Accepted)
    {
        csDlg->show();
    }
}

void MainWindow::keyWordSearchSlot()
{
    KeyWordSearchDlg *kwsDlg = new KeyWordSearchDlg(this);
    kwsDlg->show();
}

void MainWindow::typeSearchSlot()
{
    TypeSearchDlg *tsDlg = new TypeSearchDlg(this);
    tsDlg->show();
}

void MainWindow::testUDisk()
{

    QDir dir("/udisk"); //在板子上，如果检测挂载点，改为：QDir dir("/udisk")检测挂载点
    if(dir.count() == 3)
    {
        uIcon->setStyleSheet("image : url(:/image/devIcon/no.png)");
    }
    else
    {
        uIcon->setStyleSheet("image : url(:/image/devIcon/yes.png)");
    }


}

void MainWindow::regionSearchSlot()
{
    RegionSearchDlg *rsDlg = new RegionSearchDlg(this);
    connect(rsDlg, SIGNAL(sendItemId(QString)), this, SLOT(searchItemSlot(QString)));
    rsDlg->show();
}

void MainWindow::searchItemSlot(QString itemId)
{
    pageSeq = itemId.toInt() / ITEM_NUM_OF_PERPAGE + 1;
    numOfTotalItem = getNumOfTotalItem();
    displayItem();
    highLightItem(itemId.toInt());
}

void MainWindow::highLightItem(int itemId)
{
    if(displayMode)
    {
        for(int i=0; i<ITEM_NUM_OF_PERPAGE; i++)
        {
            if(mItem[i]->id->text().toInt() == itemId)
            {
                mItem[i]->setStyleSheet("background-color : yellow");
                break;
            }
        }
    }
    else
    {
        for(int i=0; i<ITEM_NUM_OF_PERPAGE; i++)
        {
            if(uItem[i]->id->text().toInt() == itemId)
            {
                mItem[i]->setStyleSheet("background-color : pink");
                break;
            }
        }
    }

}

void MainWindow::feedbackBlink()
{
    if(feedbackTemp == 0)
    {
        mItem[1]->launch->setStyleSheet("QLabel{background-color:red;}");
        feedbackTemp = 1;
    }
    else
    {
        mItem[1]->launch->setStyleSheet("QLabel{background-color:green;}");
        feedbackTemp = 0;
    }
}

void MainWindow::malfunctionBlink()
{
    if(malfunctionTemp == 0)
    {
        mItem[1]->launch->setStyleSheet("QLabel{background-color:red;}");
        malfunctionTemp = 1;
    }
    else
    {
        mItem[1]->launch->setStyleSheet("QLabel{background-color:green;}");
        malfunctionTemp = 0;
    }
}

void MainWindow::switchDisPlaySlot()
{
    if(!displayMode)
    {
        displayMode = true;
    }
    else
    {
        displayMode = false;
    }

    initItem();
}

void MainWindow::pageSeqIncSlot()
{
    if(pageSeq == maxPageSeq)
    {
        qDebug() << "最后一页";
    }
    else
    {
        pageSeq++;
        initItem();
    }
}

void MainWindow::pageSeqDesSlot()
{
    if(pageSeq == 1)
    {
        qDebug() << "已到首页";
    }
    else
    {
        pageSeq--;
        initItem();
    }
}

int MainWindow::getNumOfTotalItem()
{
    int numOfTotalItemTemp = 0;

    QSqlDatabase::database().transaction();
    QSqlQuery query;
    query.exec(QString("select id from itemInfo"));
    while(query.next())
    {
        numOfTotalItemTemp++;
    }

    QSqlDatabase::database().commit();

    return numOfTotalItemTemp;
}

int MainWindow::getMaxPages(int numOfTotalItemTemp)
{
    return numOfTotalItemTemp / ITEM_NUM_OF_PERPAGE + 1;
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    if(event->timerId() == myTimerId)
    {
        displayTime();
        switchItemStatus();
        testUDisk();
        if(malfunctionFlag != 0)
        {
            malfunctionBlink();
        }
        if(feedbackFlag != 0)
        {
            feedbackBlink();
        }
    }
}

void MainWindow::switchItemStatus()
{
    QSqlDatabase::database().transaction();
    QSqlQuery query;

    query.exec(QString("select area, ridgepole, layer, room, devName from itemInfo where id = %1").arg(itemStatusId));
    while(query.next())
    {
        QTextCodec *utf8 = QTextCodec::codecForName("UTF8");
        QString iState=query.value(0).toString() +query.value(1).toString()+query.value(2).toString() + query.value(3).toString() + query.value(4).toString();//QString(GB2312)
        QByteArray qst2qba = iState.toLatin1().data();//QString转到QByteArray.默认的QString编码方式是Latin-1,坑死了！
        QString qba2qst = utf8->toUnicode(qst2qba);//QByteArray转到QString
        itemState->setText(qba2qst);
    }

    itemStatusId++;
    QSqlDatabase::database().commit();
}

void MainWindow::showEvent(QShowEvent *)
{
    myTimerId = startTimer(1000);
}

MainWindow::~MainWindow()
{
    killTimer(myTimerId);
}
